import { defineStore } from "pinia";

export const useCart = defineStore("cart", {
  //数据状态
  state: () => {
    //初始化的时候。从 localStorage 获取初始化的数据
    let state = JSON.parse(localStorage.getItem("cartStoreState") as string);

    return {
      name: state?.value || "鲁花压榨葵花仁油5L",
      price: state?.price || 19.8,
      count: state?.count || 1,
    };
  },
  actions: {
    //减少数量
    subCount() {
      if (this.count == 1) {
        return;
      }
      this.count--;
    },

    plusCount() {
      if (this.count >= 100) {
        alert("不能再多了");
        return;
      }
      this.count++;
    },
  },

  //计算属性
  getters: {
    amount(): number {
      return parseFloat((this.price * this.count).toFixed(2));
    },
  },
});
